package leetcode.editor.cn;

//请实现一个函数按照之字形顺序打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右到左的顺序打印，第三行再按照从左到右的顺序打印，其他行以此类推。 
//
// 
//
// 例如: 
//给定二叉树: [3,9,20,null,null,15,7], 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回其层次遍历结果： 
//
// [
//  [3],
//  [20,9],
//  [15,7]
//]
// 
//
// 
//
// 提示： 
//
// 
// 节点总数 <= 1000 
// 
// Related Topics 树 广度优先搜索 二叉树 👍 163 👎 0

import java.sql.ClientInfoStatus;
import java.util.*;

public class CongShangDaoXiaDaYinErChaShuIiiLcof{
	public static void main(String[] args) {
//		Solution solution = new CongShangDaoXiaDaYinErChaShuIiiLcof().new Solution();
		TreeNode root = new TreeNode(3);
		root.left = new TreeNode(9);
		root.right = new TreeNode(20);
		root.right.left = new TreeNode(15);
		root.right.right = new TreeNode(7);
		List<List<Integer>> res = new ArrayList<>();
		res = new CongShangDaoXiaDaYinErChaShuIiiLcof().new Solution().levelOrder(root);
		System.out.println(res.toString());
	}
//leetcode submit region begin(Prohibit modification and deletion)


static class TreeNode {
  int val;
  TreeNode left;
  TreeNode right;
  TreeNode(int x) { val = x; }
}

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> res = new ArrayList<>();
		if (root == null) 	return res;
		Queue<TreeNode> queue = new LinkedList<>();
		int layerCount = 0;
		queue.offer(root);
		while (!queue.isEmpty()) {
			List<Integer> temp = new ArrayList<>();
			// queue.size()会变化，应该写在for循环的初始化中
			layerCount++;
			for (int i = queue.size(); i > 0; i--) {
				TreeNode node = queue.poll();
				temp.add(node.val);
				if (node.left != null) queue.offer(node.left);
				if (node.right != null) queue.offer(node.right);
			}
			if (layerCount % 2 == 0){
				Collections.reverse(temp);
			}
			res.add(temp);
		}
		return res;
	}
}
//leetcode submit region end(Prohibit modification and deletion)
}
